/**
 * 
 */
package server;

import gui.AccountStruct;

import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
import javax.swing.JLabel;
import javax.swing.JTable;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;

import database.Database;

import sql.QueryPackage;

import model.Model;

/**
 * @author Administrator
 *
 */
public class ListenThread extends Thread{	
	Socket _socet;
	Model _model;
	List<AccountStruct> _accounts;
	public ListenThread(Socket socket, Model model, List<AccountStruct> account) {
		this._socet = socket;
		this._model = model;
		this._accounts = account;
	}	
	@Override
	public void run() {		
		try {					
			InputStream is = _socet.getInputStream();
			ObjectInputStream ois = new ObjectInputStream(is);
			OutputStream os = _socet.getOutputStream();
			ObjectOutputStream oos = new ObjectOutputStream(os);
			while (true) {
				QueryPackage qk = (QueryPackage) ois.readObject();
				if (qk.query == null) {
					String user = qk.user;
					String pass = qk.pass;
					boolean flag = false;
					int index = 0;
					while (index < _accounts.size()) {
						AccountStruct as = _accounts.get(index);
						if (as.userName.equals(user) && as.pass.equals(pass))
							flag = true;
						index++;
					}
					if (!flag)
					{
						_socet.close();
						return;
					}
					System.out.print("Init connection, send list of database's name to client");
					List<Database> databases = _model.get_databases();
					List<String> dbs = new ArrayList<String>();
					for (int i = 0; i < databases.size(); i++) {
						dbs.add(databases.get(i).get_name());
						System.out.println(dbs.get(i));
					}
					qk.data = dbs;
					oos.writeObject(qk);
					continue;
				}				
				List<List<String>> resultSet = (List<List<String>>) _model.executeQuery(qk.query, qk.data.toString());
				qk.data = resultSet;								
				oos.writeObject(qk);	
			}											
		} catch (Exception e) {
			System.out.println(e.toString());
		}		
	}
}
